package pers.qianyu.month_202011.date_20201114;

import java.util.*;

/**
 * 34. 在排序数组中查找元素的第一个和最后一个位置
 * https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
 *
 * @author mizzle rain
 * @date 2020-11-14 22:18
 */
public class SearchRange {
    public int[] searchRange(int[] nums, int target) {
        int[] res = {-1, -1};
        if (nums == null || nums.length == 0) {
            return res;
        }
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] >= target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        if (left > nums.length - 1 || nums[left] != target) {
            return res;
        }
        res[0] = left;
        left = 0;
        right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] <= target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        if (right < 0 || nums[right] != target) {
            return new int[]{-1, -1};
        }
        res[1] = right;
        return res;
    }

    public static void main(String[] args) {
        //int[] arr = {5, 7, 7, 8, 8, 10};
        //int[] arr = {1};
        int[] arr = {2, 2};
        int[] result = new SearchRange().searchRange(arr, 3);
        System.out.println("result = " + Arrays.toString(result));
    }
}
